<template>
  <div class="register-container">
    <!-- 返回按钮 -->
    <van-icon name="arrow-left" class="back-button" @click="goBack" />

    <!-- 顶部Logo和标题 -->
    <div class="header">
      <div class="logo-container">
        <van-image width="70" height="70" src="https://fastly.jsdelivr.net/npm/@vant/assets/logo.png" round />
      </div>
      <h1 class="app-title">AI律师咨询助手</h1>
    </div>

    <!-- 注册表单 -->
    <div class="register-form">
      <van-form @submit="onSubmit">
        <van-cell-group inset>

          <van-field v-model="param.username" name="username" placeholder="请输入用户名" :rules="[
            { required: true, message: '请输入用户名' },
          ]">
            <template #left-icon>
              <van-icon name="user-circle-o" class="field-icon" />
            </template>
          </van-field>

          <!-- 手机号输入 -->
          <van-field v-model="param.phoneNumber" name="phoneNumber" placeholder="请输入11位手机号码" :rules="[
            { required: true, message: '请填写手机号' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
          ]">
            <template #left-icon>
              <van-icon name="phone-o" class="field-icon" />
            </template>
          </van-field>

          <!-- 验证码输入 -->
          <van-field v-model="param.captcha" name="captcha" placeholder="请输入4位验证码" :rules="[
            { required: true, message: '请填写验证码' },
            { pattern: /^\d{4}$/, message: '请输入4位数字验证码' }
          ]">
            <template #left-icon>
              <van-icon name="comment-o" class="field-icon" />
            </template>
            <template #button>
              <!-- <van-button size="small" type="primary" :disabled="countdown > 0"
                 @click="refreshCaptcha">
                {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
              </van-button> -->

              <div class="captcha-container" @click="refreshCaptcha" v-html="captchaSvg"></div>
            </template>
          </van-field>

          <!-- 密码输入 -->
          <van-field v-model="param.password" type="password" name="password" placeholder="请设置6-20位密码" :rules="[
            { required: true, message: '请设置密码' },
            { min: 6, max: 20, message: '密码长度6-20位' }
          ]">
            <template #left-icon>
              <van-icon name="lock" class="field-icon" />
            </template>
          </van-field>

          <!-- 确认密码 -->
          <van-field v-model="param.confirmPassword" type="password" name="confirmPassword" placeholder="请再次输入密码"
            :rules="[
              { required: true, message: '请确认密码' },
              { validator: validatePassword, message: '两次输入密码不一致' }
            ]">
            <template #left-icon>
              <van-icon name="lock" class="field-icon" />
            </template>
          </van-field>
        </van-cell-group>


        <!-- 用户协议 -->
        <div class="agreement">
          <van-checkbox v-model="agree" icon-size="16px">
            我已阅读并同意
            <span class="agreement-link" @click.stop="showAgreement">《用户协议》</span>
            和
            <span class="agreement-link" @click.stop="showPrivacy">《隐私政策》</span>
          </van-checkbox>
        </div>

        <!-- 注册按钮 -->
        <div class="submit-btn">
          <van-button round block type="primary" native-type="submit" :disabled="!agree">
            注册
          </van-button>
        </div>

        <!-- 已有账号登录 -->
        <div class="login-tip">
          <span @click="goToLogin">已有账号？<span class="login-link">立即登录</span></span>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { showNotify, showConfirmDialog } from 'vant';
import { useRouter } from 'vue-router';

import { ElMessage } from 'element-plus';

import { type RegisterFormDTO } from '@/types/login_register/RegisterFormDTO';
import { registerApi, getCaptchaApi } from '@/api/login_register';

const router = useRouter();

const phone = ref('');

const agree = ref(false);
const countdown = ref(0); // 获取验证码的倒计时时间


const param = reactive<RegisterFormDTO & { confirmPassword: string; captcha: string }>({
  username: '',
  phoneNumber: '',
  password: '',
  confirmPassword: '',
  captcha: '', // 验证码  
});

// 验证两次密码是否一致
const validatePassword = (val: string) => {
  return val === param.password;
};


// 提交注册
const onSubmit = async (values: any) => {
  console.log('register submit', values);



  try {

    const registerRequest = {
      username: param.username,
      password: param.password,
      phoneNumber: param.phoneNumber,
      captcha: param.captcha
    }

    console.log('registerRequest', registerRequest);

    const response = await registerApi(registerRequest);

    console.log('register response', response.data);

    // 假设后端返回的数据结构为 { code: number, msg: string, data?: any }
    const data = response.data; // 注意：这里不需要再.json()，axios已经处理了

    if (data.code === 200) {
      ElMessage.success('注册成功，请登录');
      router.push('/login');
    } else {
      // 显示后端返回的错误信息
      ElMessage.warning(data.msg || '注册失败，请检查输入');

      // 特殊处理验证码错误情况
      if (data.code === 400 && data.msg.includes('验证码')) {
        refreshCaptcha(); // 刷新验证码
      }
    }

  } catch (error: any) {
    // 捕获网络错误或解析错误
    console.error('注册失败:', error);

    // 显示详细的错误信息
    if (error.response) {
      // 请求已发出，服务器响应状态码不在2xx范围
      const errorMsg = error.response.data?.msg ||
        error.response.data?.message ||
        error.response.statusText;
      ElMessage.error(`注册失败: ${errorMsg}`);
    } else if (error.request) {
      // 请求已发出但没有收到响应
      ElMessage.error('网络错误，请检查网络连接');
    } else {
      // 其他错误
      ElMessage.error(error.message || '注册失败，请稍后重试');
    }
  }

  // // 重置路由栈，使login成为唯一历史记录
  // router.push('/login').then(() => {
  //   // 清除之前的所有路由历史
  //   if (window.history.state?.back) {
  //     window.history.replaceState({}, '', window.location.href);
  //   }
  // });
};

// 查看协议
const showAgreement = () => {
  showConfirmDialog({
    title: '用户协议',
    message: '这里是用户协议内容...',
    confirmButtonText: '同意',
    cancelButtonText: '取消'
  });
};

const showPrivacy = () => {
  showConfirmDialog({
    title: '隐私政策',
    message: '这里是隐私政策内容...',
    confirmButtonText: '同意',
    cancelButtonText: '取消'
  });
};

const goBack = () => {
  router.go(-1);
};

const goToLogin = () => {
  // 使用replace而不是push
  router.replace('/login');
};


/* ==================== 验证码相关逻辑 ================= */


// 验证码相关
const captchaCode = ref('');
const captchaSvg = ref(''); // 验证码图片


// 获取验证码
const getCaptcha = async () => {
  try {
    // 模拟从后端获取验证码（实际项目中替换为真实API调用）
    const response = await getCaptchaApi(param.phoneNumber);
    //const data = await response.json();
    console.log(response.data);

    if (response.data.code === 200) {

      captchaCode.value = response.data.data;

      console.log('验证码:', captchaCode.value);

      // 生成验证码SVG
      generateCaptchaSvg(captchaCode.value);

    } else {
      ElMessage.error(response.data.msg);
    }
  } catch (error) {
    console.error('获取验证码失败:', error);
    ElMessage.error('获取验证码失败，请刷新重试');
  }
};

// 生成验证码SVG
const generateCaptchaSvg = (code: string) => {
  // 创建SVG元素
  const svgWidth = 125;
  const svgHeight = 50;

  // 背景颜色
  const bgColor = `hsl(${Math.random() * 360}, 50%, 90%)`;

  // 创建干扰线
  let lines = '';
  for (let i = 0; i < 5; i++) {
    const x1 = Math.random() * svgWidth;
    const y1 = Math.random() * svgHeight;
    const x2 = Math.random() * svgWidth;
    const y2 = Math.random() * svgHeight;
    const color = `hsl(${Math.random() * 360}, 70%, 60%)`;
    lines += `<line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" stroke="${color}" stroke-width="1" />`;
  }

  // 创建验证码文本 - 使用传入的code参数
  let text = '';
  for (let i = 0; i < code.length; i++) {
    const char = code[i];
    const x = 15 + i * 20;
    const y = 25 + Math.random() * 10;
    const rotate = (Math.random() - 0.5) * 30;
    const color = `hsl(${Math.random() * 360}, 70%, 40%)`;
    const fontSize = 18 + Math.random() * 5;

    text += `
      <text x="${x}" y="${y}" 
            transform="rotate(${rotate} ${x} ${y})" 
            fill="${color}" 
            font-size="${fontSize}" 
            font-family="Arial" 
            font-weight="bold">
          ${char}
      </text>
    `;
  }

  // 组合SVG
  captchaSvg.value = `
    <svg width="${svgWidth}" height="${svgHeight}" viewBox="0 0 ${svgWidth} ${svgHeight}" xmlns="http://www.w3.org/2000/svg">
      <rect width="100%" height="100%" fill="${bgColor}" />
      ${lines}
      ${text}
    </svg>
  `;
};


// 刷新验证码
const refreshCaptcha = () => {
  // 检查手机号是否输入
  if (!param.phoneNumber) {
    ElMessage.warning('请先输入手机号');
    return;
  }

  // 验证手机号格式
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(param.phoneNumber)) {
    ElMessage.warning('请输入正确的手机号格式');
    return;
  }

  // 手机号验证通过，获取验证码
  getCaptcha();
};

/* ==================== 验证码相关逻辑 ================= */

// 组件挂载时获取验证码
onMounted(() => {
  captchaCode.value = '获取验证码'.toString();

  // 生成验证码SVG
  generateCaptchaSvg(captchaCode.value);
});




</script>


<style scoped>
.captcha-container {
  width: 100px;
  height: 40px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  border-radius: 4px;
  overflow: hidden;
}

/* 复用登录页面的样式 */
.register-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.back-button {
  position: fixed;
  top: 12px;
  left: 12px;
  font-size: 20px;
  color: #333;
  z-index: 100;
  padding: 8px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  backdrop-filter: blur(5px);
}

.header {
  width: 100%;
  padding-top: 40px;
  text-align: center;
}

.logo-container {
  margin-bottom: 10px;
}

.app-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 15px;
  letter-spacing: 1px;
}

.register-form {
  width: 100%;
  padding: 0 16px;
  box-sizing: border-box;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  margin-top: 10px;
}

:deep(.van-cell-group--inset) {
  margin: 0;
  border-radius: 8px;
  overflow: hidden;
}

:deep(.van-field) {
  padding: 14px 16px;
}

.field-icon {
  margin-right: 12px;
  color: #1989fa;
  font-size: 18px;
}

/* 验证码按钮样式 */
:deep(.van-field__button) {
  padding-left: 10px;
}

/* 用户协议样式 */
.agreement {
  margin: 15px 16px;
  font-size: 12px;
  color: #666;
}

.agreement-link {
  color: #1989fa;
}

/* 注册按钮 */
.submit-btn {
  margin: 20px 0 15px;
}

/* 登录提示 */
.login-tip {
  text-align: center;
  margin: 15px 0;
  font-size: 14px;
  color: #666;
}

.login-link {
  color: #1989fa;
  font-weight: 500;
}

/* 平板及以上设备适配 */
@media (min-width: 768px) {
  .register-form {
    max-width: 400px;
    margin: 10px auto 0;
    padding: 20px;
  }

  :deep(.van-cell-group--inset) {
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  }

  .header {
    padding-top: 60px;
  }

  .app-title {
    font-size: 20px;
    margin-bottom: 20px;
  }

  .agreement {
    margin: 15px 0;
    font-size: 14px;
  }
}
</style>